import store from '@/store'
const BASE_URL = 'https://api-hmugo-web.itheima.net/api/public/v1/'

const request = ({
  url,
  method = 'GET',
  data = {},
  header = {},
  tip = '拼命加载中...',
  // 是否为下拉刷新,默认值为false
  isPullDown = false
}) => {
  return new Promise((resolve, reject) => {
    if (!isPullDown) {
      uni.showLoading({
        title: tip,
        mask: true
      })
    }
    // 获取仓库中的token（这里也可以从本地获取）
    const token = store.getters['user/getToken']
    if (token) {
      // token一般都是通过请求头携带过去的
      header.Authorization = token
    }
    uni.request({
      url: `${BASE_URL}${url}`,
      data,
      header,
      method,
      success: ({ data, statusCode, header }) => {
        resolve(data)
      },
      fail: error => {
        reject(error)
      },
      complete: () => {
        if (!isPullDown) {
          uni.hideLoading()
        }
      }
    })
  })
}

uni.$request = request
